package com.gewe.wxChat.job.cycle;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.gewe.wxChat.manager.strategy.SanZhiStrategy;
import com.gewe.wxChat.model.entity.WxTask;
import com.gewe.wxChat.model.enums.TaskStatusEnum;
import com.gewe.wxChat.model.enums.TaskTypeEnum;
import com.gewe.wxChat.service.WxTaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 开启 领路客 定时任务
 */
// todo 取消注释开启任务
@Component
@Slf4j
public class LLKCycle {

    
    @Resource
    private WxTaskService wxTaskService;
    
    @Resource 
    private SanZhiStrategy sanZhiStrategy;
    /**
     * 每5分钟执行一次
     */
    @Scheduled(fixedRate = 5 * 60 * 1000)
    public void run() {
        // 查询近 15 分钟内的数据,并且改数据是未执行完成
        Date fifteenMinutesAgo = new Date(new Date().getTime() - 15 * 60 * 1000);
        LambdaQueryWrapper<WxTask> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WxTask::getTaskType, TaskTypeEnum.LLK_TASK.getValue());
        queryWrapper.ge(WxTask::getCreateTime, fifteenMinutesAgo); // 创建时间大于等于15分钟前
        queryWrapper.le(WxTask::getCreateTime, new Date()); // 创建时间小于等于当前时间
        queryWrapper.eq(WxTask::getTaskStatus, TaskStatusEnum.DaiChuLi.getValue());
        List<WxTask> wxTasks = wxTaskService.list(queryWrapper);
        if(wxTasks == null || wxTasks.size() == 0){
            return;
        }
        List<String> exitFormIdList = new ArrayList<>();
        List<Integer> removeIdList= new ArrayList<>();
        for (WxTask wxTask : wxTasks) {
            
            String formId=sanZhiStrategy.getKeyWord(wxTask.getContent());
            //判断这个任务是否已经执行,执行过则放弃执行，做下一个任务
            if(exitFormIdList.contains(formId)){
                removeIdList.add(wxTask.getId());
                continue;
            }
            exitFormIdList.add(formId);
            String ats="";
            String[] parts = wxTask.getContent().split(":", 2);
            //在微信群内才需要@别人
            if(wxTask.getFromUserName().contains("@chatroom") && parts.length > 0){
                ats = wxTask.getContent().split(":", 2)[0];
            }
            String result=sanZhiStrategy.start(formId, wxTask.getContent());
            if(result.contains("5分钟后重发")){
                continue;
            }
            //发送消息给对应的人
            sanZhiStrategy.sendMsg(wxTask.getAppId(),wxTask.getFromUserName(),result.toString(),ats,wxTask.getNewMsgId());
        }
        //删除掉已经执行过的任务
        if(removeIdList.size()>0){
            LambdaQueryWrapper<WxTask> removeQueryWrapper = new LambdaQueryWrapper<>();
            removeQueryWrapper.in(WxTask::getId,removeIdList);
            wxTaskService.remove(removeQueryWrapper);
        }
    }
}
